/*
 * @Description:
 * @Author: william
 * @Date: 2025-11-07 09:18:30
 * @LastEditors: william
 * @LastEditTime: 2025-11-07 11:50:59
 */
import { LingxinApiClientT2v } from '@/js_sdk/Lingxin/LingxinApiClientTtv'
import { LingxinApiClientV2v } from '@/js_sdk/Lingxin/LingxinApiClientVtv'
import AudioFileManager from '@/js_sdk/AudioFileManager/index.js'

class LingxinApiService {
  // 企业在灵芯的唯一标识
  lingxinAppId = '68ac37c7-0e27-4297-853a-06edd2fa388b'

  constructor() {}

  /**
   * 调用灵芯平台接口将文本转换成语音数据
   * @param {String} text 文本
   * @returns {String} 音频文件的路径
   */
  textToVoice(text) {
    return new Promise(async (resolve, reject) => {
      const { appId, asrLicense } = storeToRefs(useAppAsrLicenseStore())
      // 获取语音LicenseKey
      if (!asrLicense.value) {
        const { code, data } = await g_api.client.apiQueryAppAsrLicenseKey({
          appId: appId.value
        })
        if (code === 200) {
          asrLicense.value = data.asrLicense
        }
      }
      if (!asrLicense.value) {
        console.log('语音LicenseKey不存在')
        reject('语音LicenseKey不存在')
      }
      // console.log(this.lingxinAppId, appId.value, asrLicense.value)
      let client = new LingxinApiClientT2v(
        this.lingxinAppId,
        appId.value,
        asrLicense.value
      )
      client
        .textToVoice(text)
        .then(r => {
          console.log('文本转语音成功：', r)
          console.log('准备存储语音数据到文件...')
          // let saveFilePath = AudioFileManager.writeData(r)
          // resolve(saveFilePath)
          AudioFileManager.writeDataAsync(r)
            .then(saveFilePath => {
              console.log('存储完成：', saveFilePath)
              resolve(saveFilePath)
            })
            .catch(error => {
              console.log('存储语音数据到文件错误：', error)
            })
        })
        .catch(e => {
          console.log('文本转语音失败：', e)
          reject(e)
        })
        .finally(() => {
          // 无论成功或失败都会执行
          client.closeSocket()
        })
    })
  }

  /**
   * 调用灵芯平台接口将语音转换成文本指令JSON
   * @param {String} auidoFilePath 语音文件路径
   */
  voiceToText(auidoFilePath) {
    return new Promise(async (resolve, reject) => {
      const { appId, asrLicense } = storeToRefs(useAppAsrLicenseStore())
      // 获取语音LicenseKey
      if (!asrLicense.value) {
        const { code, data } = await g_api.client.apiQueryAppAsrLicenseKey({
          appId: appId.value
        })
        if (code === 200) {
          asrLicense.value = data.asrLicense
        }
      }
      if (!asrLicense.value) {
        console.log('语音LicenseKey不存在')
        reject('语音LicenseKey不存在')
      }
      // console.log(this.lingxinAppId, appId.value, asrLicense.value)
      if (!auidoFilePath) {
        reject('语音文件路径不存在')
      }
      // 拼接语音文件的完整路径
      // console.log('AppPath: ', AudioFileManager.AppPath)
      // let rootPath = this.removeSuffix(AudioFileManager.AppPath, "/files")
      // let subPath = this.removePrefix(auidoFilePath, "_doc/")
      // let fullAudioFilePath = `${rootPath}/apps/_UNI_5930F2F/doc/${subPath}`
      let fullAudioFilePath = auidoFilePath

      console.log('准备读取语音音频文件: ', fullAudioFilePath)
      // let voiceData = AudioFileManager.readData(auidoFilePath)
      // if (!voiceData || voiceData.byteLength == 0) {
      //   reject('语音文件内容为空')
      // }
      AudioFileManager.readDataAsync(fullAudioFilePath)
        .then(voiceData => {
          if (!voiceData || voiceData.byteLength == 0) {
            reject('语音文件内容为空')
          }
          let client = new LingxinApiClientV2v(
            this.lingxinAppId,
            appId.value,
            asrLicense.value
          )
          client
            .voiceToVoice(voiceData)
            .then(r => {
              console.log('语音转文本指令成功：', r)
              resolve(r)
            })
            .catch(e => {
              console.log('语音转文本指令失败：', e)
              reject(e)
            })
            .finally(() => {
              // 无论成功或失败都会执行
              client.closeSocket()
            })
        })
        .catch(e => {
          console.log(e)
          reject(e)
        })
    })
  }

  removePrefix(str, prefix) {
    if (str.startsWith(prefix)) {
      return str.slice(prefix.length)
    }
    return str
  }
  removeSuffix(str, suffix) {
    if (str.endsWith(suffix)) {
      return str.slice(0, -suffix.length)
    }
    return str
  }
}

export const lingxinApiService = new LingxinApiService()
